package com.geekaca.testthread.testfuture;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class HelloFuture {
    public static void main(String[] args) {
        /**
         * 获得线程执行的结果
         */
        Callable<String> mycall = new Mycallable(1000);
        FutureTask<String> futureTask = new FutureTask<>(mycall);
        Thread t1 = new Thread(futureTask, "Thread1");
        t1.start();

        Callable<String> my2 = new Mycallable(200);
        FutureTask<String> futureTask2 = new FutureTask<>(my2);
        Thread t2 = new Thread(futureTask2, "Thread_2");
        t2.start();


        String result = null;
        try {
            result = futureTask.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println("我的线程结果: " + result);

        String rs = null;

        try {
            rs = futureTask2.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println("第二个线程结果: " + rs);
    }
}

class Mycallable implements Callable<String> {
    private int number;

    public Mycallable(int number) {
        this.number = number;
    }

    @Override
    public String call() throws Exception {
        System.out.println("开始累加: " + number);
        int sum = 0;
        for (int i = 0; i < number; i++) {
//            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName() + " " + i);
            sum += i;
        }
        return "线程累加的结果: " + sum;
    }
}
